<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>BrowerRouter 的原理</title>
        <style>
            #result {
                width: 400px;
                height: 300px;
                border: solid 1px #ddd;
            }
        </style>
    </head>
    <body>
        <a href="/home">Home</a>
        <a href="/about">About</a>
        <hr />
        <div id="result"></div>

        <script>
            let result = document.querySelector("#result");
            //获取所有的 a 元素
            let links = document.querySelectorAll("a");
            //遍历绑定事件
            links.forEach((link) => {
                link.addEventListener("click", function (e) {
                    //1. 阻止默认行为
                    e.preventDefault();
                    //2. 存入历史与状态
                    history.pushState(
                        { msg: "我是存入的state数据" },
                        null,
                        this.href
                    ); //this 事件源  href 是 a 元素身上的属性
                    //3. 根据路径显示不同的内容
                    // console.log(location);
                    let pathname = location.pathname;
                    //判断
                    switch (pathname) {
                        case "/home":
                            result.innerHTML = "首页";
                            break;
                        case "/about":
                            result.innerHTML = "关于我们";
                            break;
                        default:
                            result.innerHTML = "404 not Found";
                            break;
                    }
                });
            });

            //绑定事件 popstate
            window.addEventListener("popstate", function () {
                // console.log(location);
                let pathname = location.pathname;
                //判断
                switch (pathname) {
                    case "/home":
                        result.innerHTML = "首页";
                        break;
                    case "/about":
                        result.innerHTML = "关于我们";
                        break;
                    default:
                        result.innerHTML = "404 not Found";
                        break;
                }
            });
        </script>
    </body>
</html>
